package com.ngkj.zmfptback.sys.filter;

import com.alibaba.fastjson.JSON;
import com.ngkj.zmfptCommon.common.util.ResultEnum;
import com.ngkj.zmfptback.sys.bean.UserEntity;
import com.ngkj.zmfptback.sys.config.JwtConfig;
import com.ngkj.zmfptback.sys.util.ResultUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 先验证token 再验证码url
 * token验证的filter
 * @author ChenHN
 * @since 2021/12/1 creation
 **/

@Slf4j
public class JWTAuthenticationTokenFilter extends BasicAuthenticationFilter {
    public JWTAuthenticationTokenFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取请求头中的Jwt的token
        String tokenHeader = request.getHeader(JwtConfig.tokenHeader);
        if (!StringUtils.isEmpty(tokenHeader) && tokenHeader.startsWith(JwtConfig.tokenPrefix)) {
            try {
                //截取jwt前缀
                String token = tokenHeader.replace(JwtConfig.tokenPrefix, "");
                // 解析jwt
                Claims claims = Jwts.parser()
                        .setSigningKey(JwtConfig.secret)
                        .parseClaimsJws(token)
                        .getBody();
                //获取用户名
                String username = claims.getSubject();
                String id = claims.getId();
                if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(id)) {
                    //获取角色
                    List<SimpleGrantedAuthority> authorities = null;
                    String authority = claims.get("authorities").toString();
                    if (!StringUtils.isEmpty(authority)) {
                        authorities = JSON.parseArray(authority, SimpleGrantedAuthority.class);
                    }
                    UserEntity userEntity = new UserEntity();
                    userEntity.setId(Integer.parseInt(claims.getId()));
                    userEntity.setUsername(claims.getSubject());
                    userEntity.setAuthorities(authorities);
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userEntity, id, authorities);
                    //设置上下文
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            } catch (ExpiredJwtException e) {
                log.info("Token过期");
                ResultUtil.responseJson(response, ResultEnum.tokenExpired);
                return ;
            }catch (Exception e){
                log.info("Token失效");
                ResultUtil.responseJson(response,ResultEnum.tokenFailure);
                return ;
            }
        }
        chain.doFilter(request,response);
        return ;
    }



}
